import React, { useState } from 'react';
import SearchHeader from './SearchHeader';
import GenericEditPage from '../GenericEditPage';
import ColumnFilterModal from './ColumnFilterModal';
import DataFilterModal from './DataFilterModal';
import openFilePreviewWindow from '../FilePreviewWindow';
import AttachmentDropdown from '../AttachmentDropdown';
import ErrorToast from '../ErrorToast';
import { 
  journalConfig, 
  conferenceConfig, 
  patentConfig, 
  softwareConfig, 
  competitionConfig, 
  projectConfig 
} from '../GenericEditPage/configs';
import './DataTable.css';

const DataTable = ({ 
  data = [], 
  total = null, // 总记录数（如果提供，则使用服务端分页）
  columns = [], 
  pageSize = 20,
  currentPage: externalCurrentPage = null, // 外部控制的当前页码（服务端分页时使用）
  showPagination = true,
  showStats = false,
  stats = [],
  showSearch = true,
  searchPlaceholder = "搜索标题、作者...",
  filterOptions = [],
  title = "软件著作权",
  titleIcon = "default",
  editType = "journal", // 新增：编辑页面类型
  loading = false, // 加载状态
  onNew = null,
  onEdit = null, // 编辑回调函数，接收 (rowData) => void
  onDelete = null, // 删除回调函数，接收 (id) => void
  onSubmit = null, // 提交编辑回调函数，接收 (formData, uploadedFiles, id, initialUploadedFiles) => Promise<void>
  onFilter = null,
  onPageChange = null, // 页码变化回调（服务端分页时使用）
  onPageSizeChange = null, // 每页数量变化回调（服务端分页时使用）
  onSearchChange = null, // 搜索词变化回调（服务端分页时使用）
  onFilterChange = null, // 筛选条件变化回调（服务端分页时使用）
  className = ''
}) => {
  // 是否使用服务端分页
  const isServerSidePagination = total !== null && onPageChange !== null;
  
  const [internalCurrentPage, setInternalCurrentPage] = useState(1);
  const [internalItemsPerPage, setInternalItemsPerPage] = useState(pageSize);
  
  // 根据是否使用服务端分页来决定使用外部还是内部状态
  const currentPage = isServerSidePagination ? (externalCurrentPage || 1) : internalCurrentPage;
  const itemsPerPage = isServerSidePagination ? pageSize : internalItemsPerPage;
  const [searchTerm, setSearchTerm] = useState('');
  const [isEditMode, setIsEditMode] = useState(false);
  const [editingData, setEditingData] = useState(null); // 编辑时的数据
  const [editError, setEditError] = useState(''); // 编辑页面的错误信息
  const [isColumnFilterOpen, setIsColumnFilterOpen] = useState(false);
  const [visibleColumns, setVisibleColumns] = useState(columns.map(col => col.key));
  const [isDataFilterOpen, setIsDataFilterOpen] = useState(false);
  const [dataFilters, setDataFilters] = useState({}); // key -> value

  // 文件预览处理函数
  const handleFilePreview = (file) => {
    if (file && file.name) {
      openFilePreviewWindow(file);
    }
  };

  // 渲染文件列表
  const renderFileList = (files, uploadAreaKey) => {
    if (!files || !Array.isArray(files) || files.length === 0) {
      return <span className="data-table__no-files">暂无文件</span>;
    }
    
    return (
      <div className="data-table__file-list">
        {files.map((file, index) => (
          <div key={index} className="data-table__file-item">
            <span 
              className="data-table__file-name"
              onClick={() => handleFilePreview(file)}
              title={`点击预览: ${file.name}`}
            >
              {file.name}
            </span>
          </div>
        ))}
      </div>
    );
  };

  // 搜索和筛选逻辑（仅前端分页时使用）
  const filteredData = isServerSidePagination 
    ? data // 服务端分页时，数据已经在服务端过滤，直接使用
    : data.filter(item => {
        const matchesSearch = !searchTerm || 
          Object.values(item).some(value => 
            String(value).toLowerCase().includes(searchTerm.toLowerCase())
          );
        // 根据数据条件筛选
        const matchesDataFilters = Object.keys(dataFilters).every(key => {
          const v = dataFilters[key];
          if (v === undefined || v === null || v === '') return true;
          const cell = item[key];
          if (cell === undefined || cell === null) return false;
          // 数字比较: 支持 ">=x", "<=x", ">x", "<x", "=x"，否则模糊包含
          if (typeof cell === 'number') {
            const str = String(v).trim();
            const num = parseFloat(str.replace(/^[<>]=?|=/, ''));
            if (isNaN(num)) return String(cell).includes(str);
            if (str.startsWith('>=')) return cell >= num;
            if (str.startsWith('<=')) return cell <= num;
            if (str.startsWith('>')) return cell > num;
            if (str.startsWith('<')) return cell < num;
            if (str.startsWith('=')) return cell === num;
            return String(cell).includes(str);
          }
          // 其他类型：字符串模糊匹配（不区分大小写）
          return String(cell).toLowerCase().includes(String(v).toLowerCase());
        });
        return matchesSearch && matchesDataFilters;
      });

  // 如果使用服务端分页，直接使用数据；否则进行前端分页
  const totalPages = isServerSidePagination 
    ? Math.ceil(total / itemsPerPage)
    : Math.ceil(filteredData.length / itemsPerPage);
  
  const currentData = isServerSidePagination 
    ? data // 服务端分页时，data 已经是当前页的过滤后数据
    : (() => {
        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = startIndex + itemsPerPage;
        return filteredData.slice(startIndex, endIndex);
      })();

  const handlePageChange = (page) => {
    if (isServerSidePagination) {
      // 服务端分页：调用外部回调
      if (onPageChange) {
        onPageChange(page);
      }
    } else {
      // 前端分页：使用内部状态
      setInternalCurrentPage(page);
    }
  };

  const handleItemsPerPageChange = (newSize) => {
    if (isServerSidePagination) {
      // 服务端分页：调用外部回调
      if (onPageSizeChange) {
        onPageSizeChange(newSize);
      }
      if (onPageChange) {
        onPageChange(1); // 改变每页数量时重置到第一页
      }
    } else {
      // 前端分页：使用内部状态
      setInternalItemsPerPage(newSize);
      setInternalCurrentPage(1);
    }
  };

  const handleSearchChange = (value) => {
    setSearchTerm(value);
    if (isServerSidePagination) {
      // 服务端分页：搜索时重置到第一页并通知父组件
      if (onSearchChange) {
        onSearchChange(value);
      }
      if (onPageChange) {
        onPageChange(1);
      }
    } else {
      // 前端分页：重置到第一页
      setInternalCurrentPage(1);
    }
  };

  const handleNew = () => {
    setEditingData(null); // 新建时清除编辑数据，确保表单为空
    setIsEditMode(true);
    if (onNew) {
      onNew();
    }
  };

  const handleBackToList = () => {
    setIsEditMode(false);
    setEditingData(null);
    setEditError(''); // 返回列表时清除错误信息
  };

  const handleEditClick = (rowData) => {
    setEditingData(rowData);
    setIsEditMode(true);
    if (onEdit) {
      onEdit(rowData);
    }
  };

  const handleOpenColumns = () => {
    setIsColumnFilterOpen(true);
  };
  const handleOpenDataFilter = () => {
    setIsDataFilterOpen(true);
  };

  const handleColumnFilterConfirm = (selectedColumnKeys) => {
    setVisibleColumns(selectedColumnKeys);
    setIsColumnFilterOpen(false);
  };

  const handleColumnFilterClose = () => {
    setIsColumnFilterOpen(false);
  };

  // 根据可见列过滤columns
  const filteredColumns = columns.filter(column => visibleColumns.includes(column.key));

  // 获取编辑配置（用于获取上传区域信息）
  const getEditConfig = () => {
    switch (editType) {
      case 'conference':
        return conferenceConfig;
      case 'patent':
        return patentConfig;
      case 'software':
        return softwareConfig;
      case 'competition':
        return competitionConfig;
      case 'project':
        return projectConfig;
      case 'journal':
      default:
        return journalConfig;
    }
  };

  const config = getEditConfig();
  
  // 使用过滤后的列，不再自动插入文件列（所有列都在页面组件中定义）
  const enhancedColumns = [...filteredColumns];

  if (isEditMode) {
    return (
      <div className={`data-table ${className}`}>
        {editError && (
          <ErrorToast 
            message={editError} 
            duration={5000}
            onClose={() => setEditError('')} 
          />
        )}
        <GenericEditPage
          title={config.title}
          icon={config.icon}
          fields={config.fields}
          uploadAreas={config.uploadAreas}
          initialData={editingData}
          recordType={editType}
          onBack={handleBackToList}
          onSubmit={async (formData, uploadedFiles, id, initialUploadedFiles) => {
            try {
              setEditError(''); // 开始提交时清除之前的错误
              if (onSubmit) {
                await onSubmit(formData, uploadedFiles, editingData?.id, initialUploadedFiles);
                // 提交成功后返回列表
                handleBackToList();
              } else {
                console.log('提交表单数据:', formData);
                console.log('上传文件:', uploadedFiles);
                handleBackToList();
              }
            } catch (error) {
              console.error('提交失败:', error);
              // 提交失败时保持编辑状态，显示错误信息，让用户修改后重试
              const errorMessage = error?.message || error?.toString() || '保存失败，请检查必填字段是否都已填写';
              setEditError(errorMessage);
            }
          }}
        />
      </div>
    );
  }

  return (
    <div className={`data-table ${className}`}>
      {showSearch && (
        <SearchHeader
          title={title}
          titleIcon={titleIcon}
          searchPlaceholder={searchPlaceholder}
          searchTerm={searchTerm}
          totalCount={isServerSidePagination ? total : filteredData.length}
          onSearchChange={handleSearchChange}
          onNew={handleNew}
          onColumns={handleOpenColumns}
          onFilter={handleOpenDataFilter}
          showNew={!!onNew}
          showColumns={true}
          showFilter={true}
        />
      )}

      <div className="data-table__container">
        <table className="data-table__table">
          <thead className="data-table__header">
            <tr>
              {enhancedColumns.map((column, index) => (
                <th 
                  key={index} 
                  className={`data-table__th ${column.key === 'actions' ? 'data-table__th--actions' : ''}`} 
                  style={{ width: column.width }}
                >
                  {column.title}
                </th>
              ))}
            </tr>
          </thead>
          <tbody className="data-table__body">
            {loading ? (
              <tr>
                <td colSpan={enhancedColumns.length} className="data-table__loading">
                  <div style={{ padding: '40px', textAlign: 'center', color: '#666' }}>
                    加载中...
                  </div>
                </td>
              </tr>
            ) : currentData.length === 0 ? (
              <tr>
                <td colSpan={enhancedColumns.length} className="data-table__empty">
                  <div style={{ padding: '40px', textAlign: 'center', color: '#999' }}>
                    暂无数据
                  </div>
                </td>
              </tr>
            ) : (
              currentData.map((row, rowIndex) => (
                <tr key={row.id || rowIndex} className="data-table__row">
                  {enhancedColumns.map((column, colIndex) => (
                    <td 
                      key={colIndex} 
                      className={`data-table__td ${column.key === 'actions' ? 'data-table__td--actions' : ''}`}
                    >
                      {column.render ? column.render(row[column.key], row, { onEdit: handleEditClick, onDelete }) : row[column.key]}
                    </td>
                  ))}
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {showPagination && (
        <div className={`data-table__pagination ${totalPages === 1 ? 'data-table__pagination--single-page' : ''}`}>
          <div className="data-table__pagination-left">
            <select 
              className="data-table__page-size"
              value={itemsPerPage}
              onChange={(e) => handleItemsPerPageChange(Number(e.target.value))}
            >
              <option value={10}>10条/页</option>
              <option value={20}>20条/页</option>
              <option value={50}>50条/页</option>
            </select>
          </div>
          
          {totalPages > 1 && (
            <>
              <div className="data-table__pagination-center">
                <button 
                  className="data-table__page-btn"
                  disabled={currentPage === 1}
                  onClick={() => handlePageChange(currentPage - 1)}
                >
                  ‹
                </button>
                
                {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                  const pageNum = i + 1;
                  return (
                    <button
                      key={pageNum}
                      className={`data-table__page-btn ${currentPage === pageNum ? 'data-table__page-btn--active' : ''}`}
                      onClick={() => handlePageChange(pageNum)}
                    >
                      {pageNum}
                    </button>
                  );
                })}
                
                {totalPages > 5 && (
                  <>
                    <span className="data-table__page-ellipsis">...</span>
                    <button
                      className={`data-table__page-btn ${currentPage === totalPages ? 'data-table__page-btn--active' : ''}`}
                      onClick={() => handlePageChange(totalPages)}
                    >
                      {totalPages}
                    </button>
                  </>
                )}
                
                <button 
                  className="data-table__page-btn"
                  disabled={currentPage === totalPages}
                  onClick={() => handlePageChange(currentPage + 1)}
                >
                  ›
                </button>
              </div>
              
              <div className="data-table__pagination-right">
                <span className="data-table__page-info">
                  跳至
                  <input 
                    type="number" 
                    className="data-table__page-input"
                    min="1"
                    max={totalPages}
                    value={currentPage}
                    onChange={(e) => handlePageChange(Number(e.target.value))}
                  />
                  <span className="data-table__page-total">/ {totalPages}页</span>
                </span>
              </div>
            </>
          )}
        </div>
      )}

      {/* 显示列弹窗 */}
      <ColumnFilterModal
        isOpen={isColumnFilterOpen}
        onClose={handleColumnFilterClose}
        onConfirm={handleColumnFilterConfirm}
        availableColumns={columns}
        selectedColumns={visibleColumns}
        title="选择显示列"
      />

      {/* 数据筛选弹窗 */}
      <DataFilterModal
        isOpen={isDataFilterOpen}
        onClose={() => setIsDataFilterOpen(false)}
        onConfirm={(filters) => { 
          setDataFilters(filters);
          if (isServerSidePagination) {
            // 服务端分页：通知父组件筛选条件变化
            if (onFilterChange) {
              onFilterChange(filters);
            }
            if (onPageChange) {
              onPageChange(1);
            }
          } else {
            setInternalCurrentPage(1);
          }
        }}
        columns={columns}
        data={data}
        initialFilters={dataFilters}
        title="筛选"
      />
    </div>
  );
};

export default DataTable;
